/**
 * Created by neal on 12/16/16.
 */

var Config = {
    registerUrl: '/api/accounts/register',
    checkcodeUrl: '/api/accounts/checkcode'
};

$.validator.setDefaults({
    highlight: function (e) {
        $(e).closest(".form-group").removeClass("has-success").addClass("has-error")
    }, success: function (e) {
        e.closest(".form-group").removeClass("has-error").addClass("has-success");
    }, errorElement: "span", errorPlacement: function (e, r) {
        e.appendTo(r.is(":radio") || r.is(":checkbox") ? r.parent().parent().parent() : r.parent())
    }, errorClass: "help-block m-b-none", validClass: "help-block m-b-none"
});
$(document).ready(function () {
    $(".i-checks").iCheck({checkboxClass: "icheckbox_square-green", radioClass: "iradio_square-green",});
    jQuery.validator.addMethod('agree', function (value) {
        return (value == 'on');
    }, "请阅读注册协议");
    $("#ajaxform").validate({
        rules: {
            agree: {
                agree: true
            }
        }
    });
   $("#register").click(function () {
       if ($('#ajaxform').valid()) {
           $.ajax(
               {
                   url : Config.registerUrl,
                   type: "POST",
                   data: $("#ajaxform").serializeArray(),
                   dataType: "json",
                   success:function(data, textStatus, jqXHR)
                   {
                       if(data && data.type == 'SUCCESS'){
                           toastr.success(data.msg, data.title);
                           window.location.href="/login";
                       }else {
                           toastr.error(data.msg, data.title);
                       }
                   },
                   error: function(jqXHR, textStatus, errorThrown)
                   {
                       toastr.error(errorThrown, textStatus);
                   }
               });
           return false;
       }
   });
    $("#GetCheckCode").click(function () {
        var phone = $("#ajaxform input[name=username]").val();
        if(!phone){
            toastr.error("请输入手机号");
            return false;
        }
       $.ajax(
       {
           url : Config.checkcodeUrl,
           type: "GET",
           data: {username: phone},
           dataType: "json",
           success:function(data, textStatus, jqXHR)
           {
               if(data && data.type == 'SUCCESS'){
                   toastr.success(data.msg, data.title);
                   $('#GetCheckCode').text("已发送到您的手机").attr("disabled","disabled");
               }else {
                   toastr.error(data.msg, data.title);
               }
           },
           error: function(jqXHR, textStatus, errorThrown)
           {
               toastr.error(errorThrown, textStatus);
           }
       });
        return false;
   });
});